package com.yx.frame.builder.code;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;

import com.yx.frame.builder.validate.ServiceBuilderConfigManager;

public class IosClientCode {
	String rootPath;
	String jsFileName;
	String jsControlName;
	OutputStreamWriter jsWriter = null;
	OutputStreamWriter jsHeadWriter = null;
	String host;
	int port;
	public IosClientCode(String rootPath, String jsFileName, String jsControlName)throws Exception {
		this.rootPath = rootPath;
		this.jsFileName = jsFileName;
		this.jsControlName = jsControlName;
		File path = new File(rootPath + "/client/ios/");
		if (!path.exists()) {
			path.mkdirs();
		}
		String jsFilePath = rootPath + "/client/ios/" + jsControlName + ".m";
		File file = new File(jsFilePath);
		if (file.exists()) {
			file.delete();
		}
		String serverUrl=ServiceBuilderConfigManager.getInstance().getServerUrl();
		URL aURL = new URL(serverUrl);
		host = aURL.getHost();
		port = aURL.getPort();
		jsWriter = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
		String jsHeadFilePath = rootPath + "/client/ios/" + jsControlName + ".h";
		File headFile = new File(jsHeadFilePath);
		if (headFile.exists()) {
			headFile.delete();
		}
		jsHeadWriter = new OutputStreamWriter(new FileOutputStream(headFile), "UTF-8");
	}
	public void writePublic() throws Exception {
		jsHeadWriter.write("#import <Foundation/Foundation.h>\r\n");
		jsHeadWriter.write("@interface "+jsControlName+" : NSObject\r\n");
		jsHeadWriter.write("+(void)setUID:(NSString *)uid;\r\n");
		jsHeadWriter.write("+(NSString *)getUID;\r\n");
		jsHeadWriter.write("+(void)setUser:(NSString *)userName Password:(NSString *)password;\r\n");
		jsHeadWriter.write("-(NSString *)getDownloadUrl:(NSString *)fileName;\r\n");
		jsHeadWriter.write("-(NSDictionary*)fileUpload:(NSString *)filePath;\r\n");
		
		jsWriter.write("#import \""+jsControlName+".h\"\r\n");
		jsWriter.write("#import <CommonCrypto/CommonDigest.h>\r\n");
		jsWriter.write("#import <CommonCrypto/CommonCryptor.h>\r\n");
		jsWriter.write("#import <sys/socket.h>\r\n");
		jsWriter.write("#import <netinet/in.h>\r\n");
		jsWriter.write("#import <arpa/inet.h>\r\n");
		jsWriter.write("#import <unistd.h>\r\n");
		jsWriter.write("@implementation "+jsControlName+"\r\n");
		jsWriter.write("static NSString *_pKey = @\"ShhOt0m5gfMpsLjP\";\r\n");
		jsWriter.write("static NSString *_BOUNDARY = @\"----WebKitFormBoundaryT1HoybnYeFOGFlBR\";\r\n");
		jsWriter.write("static const char encodingTable[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\r\n");
		jsWriter.write("static NSString *_host = @\""+host+"\";\r\n");
		jsWriter.write("static int _port = "+port+";\r\n");
		jsWriter.write("static NSString *_Uid = @\"wukai\";\r\n");		
		jsWriter.write("+(void)setUID:(NSString *)uid{\r\n");
		jsWriter.write("    _Uid=uid;\r\n");
		jsWriter.write("}\r\n");
		jsWriter.write("+(NSString *)getUID{\r\n");
		jsWriter.write("    return _Uid;\r\n");
		jsWriter.write("}\r\n");
		jsWriter.write("+(void)setUser:(NSString *)userName Password:(NSString *)password{\r\n");		    
		jsWriter.write("    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];\r\n");
		jsWriter.write("    long nowTime =[dat timeIntervalSince1970]*1000;\r\n");
		jsWriter.write("    NSString *timestamp = [NSString stringWithFormat:@\"%ld\", nowTime];\r\n");
		jsWriter.write("    NSString *keyString = [password stringByAppendingString:timestamp];\r\n");
		jsWriter.write("    NSString *md5Key = [self MD5:keyString];\r\n");
		jsWriter.write("    if (md5Key.length > 16) {\r\n");
		jsWriter.write("        md5Key = [md5Key substringToIndex:16];\r\n");
		jsWriter.write("    }\r\n");
		jsWriter.write("    NSData *timestempData = [timestamp dataUsingEncoding:NSUTF8StringEncoding];\r\n");
		jsWriter.write("    NSString *encrypted = [self AESEncrypt:timestempData Key:md5Key];\r\n");
		jsWriter.write("    NSString *sigTxt = [NSString stringWithFormat:@\"[\\\"%@\\\",\\\"%@\\\",\\\"%@\\\"]\", userName, encrypted, timestamp];\r\n");
		jsWriter.write("    NSData *signTxtData = [sigTxt dataUsingEncoding:NSUTF8StringEncoding];\r\n");
		jsWriter.write("    NSString *signEncrypted = [self AESEncrypt:signTxtData Key:_pKey];\r\n");
		jsWriter.write("    _Uid= signEncrypted; \r\n");   
		jsWriter.write("}\r\n");
		
		jsWriter.write("- (NSString *)MD5:(NSString *)str {\r\n");    
		jsWriter.write("    const char *cStr = [str UTF8String];\r\n");
		jsWriter.write("    unsigned long length = strlen(cStr);\r\n");
		jsWriter.write("    unsigned char result[16];\r\n");
		jsWriter.write("    CC_MD5(cStr, (CC_LONG)length, result);\r\n");    
		jsWriter.write("    NSMutableString *secureString = [NSMutableString string];\r\n");
		jsWriter.write("    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){\r\n");
		jsWriter.write("        [secureString appendFormat:@\"%02x\", result[i]];\r\n");
		jsWriter.write("    }\r\n");
		jsWriter.write("    return secureString;\r\n");    
		jsWriter.write("}\r\n");
		jsWriter.write("- (NSString *)encode:(NSData*)data {\r\n");    
		jsWriter.write("    if ([data length] == 0)\r\n");
		jsWriter.write("        return @\"\"; \r\n");   
		jsWriter.write("    char *characters = malloc((([data length] + 2) / 3) * 4);\r\n");
		jsWriter.write("    if (characters == NULL)\r\n");
		jsWriter.write("        return nil;\r\n");
		jsWriter.write("    NSUInteger length = 0;\r\n");    
		jsWriter.write("    NSUInteger i = 0;\r\n");
		jsWriter.write("    while (i < [data length])\r\n");
		jsWriter.write("    {\r\n");
		jsWriter.write("        char buffer[3] = {0,0,0};\r\n");
		jsWriter.write("        short bufferLength = 0;\r\n");
		jsWriter.write("        while (bufferLength < 3 && i < [data length])\r\n");
		jsWriter.write("            buffer[bufferLength++] = ((char *)[data bytes])[i++]; \r\n");       
		jsWriter.write("        characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];\r\n");
		jsWriter.write("        characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];\r\n");
		jsWriter.write("        if (bufferLength > 1)\r\n");
		jsWriter.write("            characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];\r\n");
		jsWriter.write("        else characters[length++] = '=';\r\n");
		jsWriter.write("        if (bufferLength > 2)\r\n");
		jsWriter.write("            characters[length++] = encodingTable[buffer[2] & 0x3F];\r\n");
		jsWriter.write("        else characters[length++] = '=';\r\n");
		jsWriter.write("    }\r\n");    
		jsWriter.write("    return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];\r\n");
		jsWriter.write("}\r\n");
		jsWriter.write("-(NSString *)AESEncrypt:(NSData *)srcData Key:(NSString*)key{\r\n");
		jsWriter.write("    char keyPtr[kCCKeySizeAES128+1];\r\n");
		jsWriter.write("    bzero(keyPtr, sizeof(keyPtr));\r\n");
		jsWriter.write("    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];\r\n");    
		jsWriter.write("    char ivPtr[kCCKeySizeAES128+1];\r\n");
		jsWriter.write("    memset(ivPtr, 0, sizeof(ivPtr));\r\n");
		jsWriter.write("    [key getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];\r\n");    
		jsWriter.write("    NSUInteger dataLength = [srcData length];\r\n");
		jsWriter.write("    size_t bufferSize = dataLength + kCCBlockSizeAES128;\r\n");
		jsWriter.write("    void *buffer = malloc(bufferSize);\r\n");
		jsWriter.write("    size_t numBytesEncrypted = 0;\r\n");
		jsWriter.write("    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,\r\n");
		jsWriter.write("                                          kCCAlgorithmAES128,\r\n");
		jsWriter.write("                                          kCCOptionPKCS7Padding,\r\n");
		jsWriter.write("                                          keyPtr,\r\n");
		jsWriter.write("                                          kCCBlockSizeAES128,\r\n");
		jsWriter.write("                                          ivPtr,\r\n");
		jsWriter.write("                                          [srcData bytes],\r\n");
		jsWriter.write("                                          dataLength,\r\n");
		jsWriter.write("                                          buffer,\r\n");
		jsWriter.write("                                          bufferSize,\r\n");
		jsWriter.write("                                          &numBytesEncrypted);\r\n");
		jsWriter.write("    if (cryptStatus == kCCSuccess) {\r\n");        
		jsWriter.write("        NSData *data = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];\r\n");
		jsWriter.write("        return [self encode:data];\r\n");
		jsWriter.write("    } \r\n");   
		jsWriter.write("    free(buffer);\r\n");
		jsWriter.write("    return nil;\r\n");
		jsWriter.write("}\r\n");
		
		jsWriter.write("- (NSDictionary*)post:(NSInteger)actionId asyncService:(BOOL)asyncService Data:(NSDictionary*)data {\r\n");    
		jsWriter.write("    NSNumber *actionIDNumber = [NSNumber numberWithInteger:actionId];\r\n");
		jsWriter.write("    NSNumber *asyncServiceNumber = [NSNumber numberWithBool:asyncService];\r\n");
		jsWriter.write("    NSMutableDictionary *requestData = [[NSMutableDictionary alloc]initWithCapacity:1];\r\n");
		jsWriter.write("    [requestData setObject:actionIDNumber forKey:@\"ActionId\"];\r\n");
		jsWriter.write("    [requestData setObject:[self getUID] forKey:@\"UId\"];\r\n");
		jsWriter.write("    [requestData setObject:asyncServiceNumber forKey:@\"AsyncService\"];\r\n");
		jsWriter.write("    [requestData setObject:data forKey:@\"RequestData\"];\r\n");
		jsWriter.write("    NSString *jsonString = nil;\r\n");
		jsWriter.write("    NSError *error;\r\n");
		jsWriter.write("    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestData\r\n");
		jsWriter.write("                                                       options:NSJSONWritingPrettyPrinted\r\n");
		jsWriter.write("                                                        error:&error];\r\n");
		jsWriter.write("    if (! jsonData) {\r\n");
		jsWriter.write("        return nil;\r\n");
		jsWriter.write("    }\r\n");
		jsWriter.write("    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];\r\n");
		jsWriter.write("    jsonString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,\r\n");
		jsWriter.write("                                                                                             (CFStringRef)jsonString,\r\n");
		jsWriter.write("                                                                                             NULL,\r\n");
		jsWriter.write("                                                                                             CFSTR(\"!*'();:@&=+$,/?%#[]\"),\r\n");
		jsWriter.write("                                                                                             kCFStringEncodingUTF8));\r\n");
		jsWriter.write("    NSInteger length = jsonString.length;\r\n");
		jsWriter.write("    NSString *lengthString = [NSString stringWithFormat:@\"%ld\", length];\r\n");
		jsWriter.write("    NSString *request = [[NSString alloc]init];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"POST /JsonRemote HTTP/1.1\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Cache-Control: no-cache\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Pragma: no-cache\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"User-Agent: JavaSocket/1.8.0_31\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Host: \"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:_host];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Connection: close\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Content-Type: application/x-www-form-urlencoded; charset=utf-8\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Content-Length: \"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:lengthString];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:jsonString];\r\n");
		jsWriter.write("    int err;\r\n");
		jsWriter.write("    int fd=socket(AF_INET, SOCK_STREAM, 0);\r\n");
		jsWriter.write("    BOOL success=(fd!=-1);\r\n");
		jsWriter.write("    struct sockaddr_in addr;\r\n");
		jsWriter.write("    if (success) {\r\n");
		jsWriter.write("        struct sockaddr_in peeraddr;\r\n");
		jsWriter.write("        memset(&peeraddr, 0, sizeof(peeraddr));\r\n");
		jsWriter.write("        peeraddr.sin_len=sizeof(peeraddr);\r\n");
		jsWriter.write("        peeraddr.sin_family=AF_INET;\r\n");
		jsWriter.write("        peeraddr.sin_port=htons(_port);\r\n");
		jsWriter.write("        const char *host = [_host UTF8String];\r\n");
		jsWriter.write("        peeraddr.sin_addr.s_addr=inet_addr(host);\r\n");
		jsWriter.write("        socklen_t addrLen;\r\n");
		jsWriter.write("        addrLen =sizeof(peeraddr);\r\n");
		jsWriter.write("        err=connect(fd, (struct sockaddr *)&peeraddr, addrLen);\r\n");
		jsWriter.write("        success=(err==0);\r\n");
		jsWriter.write("        if (success) {\r\n");
		jsWriter.write("            err =getsockname(fd, (struct sockaddr *)&addr, &addrLen);\r\n");
		jsWriter.write("            success=(err==0);\r\n");
		jsWriter.write("            if (success) {\r\n");
		jsWriter.write("                const char *requestChar = [request UTF8String];\r\n");
		jsWriter.write("                send(fd, requestChar, strlen(requestChar), 0);\r\n");
		jsWriter.write("                 char socketbuffer[1024];\r\n");
		jsWriter.write("                 char allreadBuffer[1024 * 128];//(char*)malloc(0);\r\n");
		jsWriter.write("                  memset(allreadBuffer, '\\0', 1024 * 128);\r\n");
		jsWriter.write("                 ssize_t len=0;\r\n");
		jsWriter.write("                 while((len=recv(fd, socketbuffer, 1023, 0))>0){\r\n");
		jsWriter.write("                     char readBuffer[len];\r\n");
		jsWriter.write("                     strcpy(readBuffer, socketbuffer);\r\n");
		jsWriter.write("                     memset(socketbuffer, '\\0', 1024);\r\n");
		jsWriter.write("                     strcat(allreadBuffer, readBuffer);\r\n");
		jsWriter.write("                     memset(readBuffer, '\\0', len);\r\n");
		jsWriter.write("                 }\r\n");
		jsWriter.write("                 close(fd);\r\n");
		jsWriter.write("                 long position = strlen(allreadBuffer);\r\n");
		jsWriter.write("                 while (allreadBuffer[position] != 0x7D) {\r\n");
		jsWriter.write("                    allreadBuffer[position] = '\\0';\r\n");
		jsWriter.write("                    position--;\r\n");
		jsWriter.write("                }\r\n");
		jsWriter.write("                position = strlen(allreadBuffer);\r\n");
		jsWriter.write("                int i = 0;\r\n");
		jsWriter.write("                while (allreadBuffer[i]!= 0x7B && i < position) {\r\n");
		jsWriter.write("                    allreadBuffer[i] = 0x20;\r\n");
		jsWriter.write("                     i++;\r\n");
		jsWriter.write("                }\r\n");     
		jsWriter.write("                NSData *data1 = [NSData dataWithBytes:allreadBuffer length:position];\r\n");
		jsWriter.write("                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];\r\n");
		jsWriter.write("                return json;\r\n");			
		jsWriter.write("            }\r\n");
		jsWriter.write("        }\r\n");
		jsWriter.write("    }\r\n");
		jsWriter.write("    return nil;\r\n");
		jsWriter.write("}\r\n");
		jsWriter.write("-(NSString *)getDownloadUrl:(NSString *)fileName {\r\n");
		jsWriter.write("    NSString *uid = [self getUID];\r\n");
		jsWriter.write("    uid = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,\r\n");
		jsWriter.write("                                                                                       (CFStringRef)uid,\r\n");
		jsWriter.write("                                                                                       NULL,\r\n");
		jsWriter.write("                                                                                       CFSTR(\"!*'();:@&=+$,/?%#[]\"),\r\n");
		jsWriter.write("                                                                                       kCFStringEncodingUTF8));\r\n");
		jsWriter.write("    NSString *url = [NSString new];\r\n");
		jsWriter.write("    url = [NSString stringWithFormat:@\"http://%@:%d/Download?UId=%@&File=%@\", _host, _port, uid, fileName];\r\n");
		jsWriter.write("    return url;\r\n");
		jsWriter.write("}\r\n");
		
		jsWriter.write("- (NSDictionary*)fileUpload:(NSString *)filePath  {\r\n");
		jsWriter.write("	NSDictionary *dis =  [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];\r\n");
		jsWriter.write("    NSNumber *fileSizeNumber = [dis objectForKey:NSFileSize];\r\n");
		jsWriter.write("	NSInteger fileSizeInteger = [fileSizeNumber integerValue];	\r\n");
		jsWriter.write("	NSFileHandle *uploadFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; \r\n"); 
		jsWriter.write("	NSString *uid = [self getUID];\r\n");
		jsWriter.write("	NSString *fileName = [filePath lastPathComponent];  ;\r\n");
			
		jsWriter.write("	NSString *formInfo = [[NSString alloc]init];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"--\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:_BOUNDARY];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"Content-Disposition: form-data; name=\\\"UId\\\"\\r\\n\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:uid];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"--\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:_BOUNDARY];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"Content-Disposition: form-data; name=\\\"file1\\\"; filename=\\\"\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:fileName];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"\\\"\\r\\n\"];\r\n");
		jsWriter.write("	formInfo = [formInfo stringByAppendingString:@\"Content-Type: image/jpeg\\r\\n\\r\\n\"];\r\n");
			
		jsWriter.write("	NSString *endInfo = [[NSString alloc]init];\r\n");
		jsWriter.write("	endInfo = [endInfo stringByAppendingString:@\"\\r\\n--\"];\r\n");
		jsWriter.write("	endInfo = [endInfo stringByAppendingString:_BOUNDARY];\r\n");
		jsWriter.write("	endInfo = [endInfo stringByAppendingString:@\"--\\r\\n\"];\r\n");
				
		jsWriter.write("	NSInteger htmlLength = formInfo.length+endInfo.length+fileSizeInteger;\r\n");
		jsWriter.write("    NSString *htmlLengthString = [NSString stringWithFormat:@\"%ld\", (long)htmlLength];\r\n");
		jsWriter.write("    NSString *request = [[NSString alloc]init];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"POST /FileUpload HTTP/1.1\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Cache-Control: no-cache\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Pragma: no-cache\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"User-Agent: JavaSocket/1.8.0_31\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Host: \"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:_host];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Connection: close\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Content-Type: multipart/form-data; boundary=\"];\r\n");
		jsWriter.write("	request = [request stringByAppendingString:_BOUNDARY];\r\n");
		jsWriter.write("	request = [request stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"Content-Length: \"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:htmlLengthString];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:@\"\\r\\n\"];\r\n");
		jsWriter.write("    request = [request stringByAppendingString:formInfo];\r\n");
			
		jsWriter.write("    int err;\r\n");
		jsWriter.write("    int fd=socket(AF_INET, SOCK_STREAM, 0);\r\n");
		jsWriter.write("    BOOL success=(fd!=-1);\r\n");
		jsWriter.write("    struct sockaddr_in addr;\r\n");
		jsWriter.write("    if (success) {\r\n");
		jsWriter.write("        struct sockaddr_in peeraddr;\r\n");
		jsWriter.write("        memset(&peeraddr, 0, sizeof(peeraddr));\r\n");
		jsWriter.write("        peeraddr.sin_len=sizeof(peeraddr);\r\n");
		jsWriter.write("        peeraddr.sin_family=AF_INET;\r\n");
		jsWriter.write("        peeraddr.sin_port=htons(_port);\r\n");
		jsWriter.write("        const char *host = [_host UTF8String];\r\n");
		jsWriter.write("        peeraddr.sin_addr.s_addr=inet_addr(host);\r\n");
		jsWriter.write("        socklen_t addrLen;\r\n");
		jsWriter.write("        addrLen =sizeof(peeraddr);\r\n");
		jsWriter.write("        err=connect(fd, (struct sockaddr *)&peeraddr, addrLen);\r\n");
		jsWriter.write("        success=(err==0);\r\n");
		jsWriter.write("        if (success) {\r\n");
		jsWriter.write("            err =getsockname(fd, (struct sockaddr *)&addr, &addrLen);\r\n");
		jsWriter.write("            success=(err==0);\r\n");
		jsWriter.write("            if (success) {\r\n");
		jsWriter.write("                const char *requestChar = [request UTF8String];\r\n");
		jsWriter.write("				const char *endInfoChar = [endInfo UTF8String];\r\n");
		jsWriter.write("                send(fd, requestChar, strlen(requestChar), 0);\r\n");
		jsWriter.write("				NSInteger    fileRemainLenght = fileSizeInteger ;\r\n");
		jsWriter.write("				while(fileRemainLenght>0){	\r\n");			
		jsWriter.write("					NSData *fileBuffer = [uploadFileHandle readDataOfLength:(8192)];\r\n");
		jsWriter.write("					NSInteger fileBufferLenght=[fileBuffer length];\r\n");
		jsWriter.write("					const char* fileCharBuffer=[fileBuffer bytes];\r\n");
		jsWriter.write("					send(fd, fileCharBuffer, fileBufferLenght, 0);\r\n");
		jsWriter.write("					fileRemainLenght=fileRemainLenght-fileBufferLenght;\r\n");
		jsWriter.write("				}\r\n");				
		jsWriter.write("				send(fd, endInfoChar, strlen(endInfoChar), 0);	\r\n");			
		jsWriter.write("                char socketbuffer[1024];\r\n");
		jsWriter.write("                char allreadBuffer[1024 * 128];//(char*)malloc(0);\r\n");
		jsWriter.write("                memset(allreadBuffer, '\0', 1024 * 128);\r\n");
		jsWriter.write("                ssize_t len=0;\r\n");
		jsWriter.write("                while((len=recv(fd, socketbuffer, 1023, 0))>0){\r\n");
		jsWriter.write("                    char readBuffer[len];\r\n");
		jsWriter.write("                    strcpy(readBuffer, socketbuffer);\r\n");
		jsWriter.write("                    memset(socketbuffer, '\0', 1024);\r\n");
		jsWriter.write("                    strcat(allreadBuffer, readBuffer);\r\n");
		jsWriter.write("                    memset(readBuffer, '\0', len);\r\n");
		jsWriter.write("                }\r\n");
		jsWriter.write("                close(fd);\r\n");
		jsWriter.write("                long position = strlen(allreadBuffer);\r\n");
		jsWriter.write("                while (allreadBuffer[position] != 0x7D) {\r\n");
		jsWriter.write("                    allreadBuffer[position] = '\0';\r\n");
		jsWriter.write("                    position--;\r\n");
		jsWriter.write("                }\r\n");
		jsWriter.write("                position = strlen(allreadBuffer);\r\n");
		jsWriter.write("                int i = 0;\r\n");
		jsWriter.write("                while (allreadBuffer[i]!= 0x7B && i < position) {\r\n");
		jsWriter.write("                    allreadBuffer[i] = 0x20;\r\n");
		jsWriter.write("                     i++;\r\n");
		jsWriter.write("                }\r\n");
		jsWriter.write("                NSData *data1 = [NSData dataWithBytes:allreadBuffer length:position];\r\n");
		jsWriter.write("                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];\r\n");
		jsWriter.write("                return json;\r\n");
		jsWriter.write("            }\r\n");
		jsWriter.write("        }\r\n");
		jsWriter.write("    }\r\n");
		jsWriter.write("    return nil;\r\n");
		jsWriter.write("}\r\n");

	}
	public void write(String str)throws Exception{
		jsWriter.write(str);
		jsWriter.flush();
	}
	public void head(String str)throws Exception{
		jsHeadWriter.write(str);
		jsHeadWriter.flush();
	}

	public void close() throws Exception {
		jsWriter.write("@end\r\n");
		jsWriter.close();
		jsHeadWriter.write("@end\r\n");
		jsHeadWriter.close();
	}

}
